<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>VT Scientific Target List</title>
    <link href="resources/bootstrap.min.css" rel="stylesheet">
    <style>
        .title {
            text-align: center;
            margin: 20px 0;
            font-weight: bold;
        }
        .summary {
            margin-bottom: 20px;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 5px;
        }
        .filters {
            margin-bottom: 20px;
            padding: 15px;
            background-color: #e9ecef;
            border-radius: 5px;
        }
        table {
            width: 100%;
            margin-top: 20px;
        }
        th {
            background-color: #343a40;
            color: white;
            position: sticky;
            top: 0;
        }
        tr:nth-child(even) {
            background-color: #f2f2f2;
        }
        .filter-control {
            margin-right: 15px;
            margin-bottom: 10px;
        }
        .data-link {
            cursor: pointer;
            color: #0d6efd;
            text-decoration: underline;
            margin: 0 5px;
        }
        .no-data {
            color: #6c757d;
            font-style: italic;
        }
    </style>
</head>
<body>

    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container-fluid">
          <a class="navbar-brand" href="#">SVOM/VT</a>
          <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
            aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>
          <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav ms-auto">
              <li class="nav-item">
                <a class="nav-link" href="/vtfollowupep/index.html" target="_blank">Home</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="/vtfollowupep/analysis-preview.html" target="_blank">LC Preview</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#" target="_blank">Refined Data</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#" target="_blank">About</a>
              </li>
            </ul>
          </div>
        </div>
      </nav>
      

    <div class="container">
        <h1 class="title">SVOM/VT high-level products</h1>
        
        <div class="filters">
            <div class="row">
                <div class="col-md-4">
                    <label for="yearFilter" class="form-label">Filter by Year:</label>
                    <select id="yearFilter" class="form-select filter-control">
                        <option value="all">All Years</option>
                        <!-- 年份选项将在这里动态加载 -->
                    </select>
                </div>
                <div class="col-md-4">
                    <label for="typeFilter" class="form-label">Filter by Type:</label>
                    <select id="typeFilter" class="form-select filter-control">
                        <option value="all">All Types</option>
                        <!-- 类型选项将在这里动态加载 -->
                    </select>
                </div>
                <div class="col-md-4">
                    <label for="searchInput" class="form-label">Search by Name:</label>
                    <input type="text" id="searchInput" class="form-control filter-control" placeholder="Enter target name...">
                </div>
            </div>
        </div>
        
        <div class="summary" id="summary">
            <!-- 统计信息将在这里动态加载 -->
        </div>
        
        <div class="table-responsive">
            <table class="table table-striped table-bordered">
                <thead class="thead-dark">
                    <tr>
                        <th>Name</th>
                        <th>Mission</th>
                        <th>Data</th>
                        <th>Trigger Time(UTC)</th>
                        <th>R.A.(J2000)</th>
                        <th>Dec.(J2000)</th>
                        <th>Error (arcsec)</th>
                        <th>Refined Date(UTC)</th>
                        <th>Note</th>
                    </tr>
                </thead>
                <tbody id="targetTable">
                    <!-- 目标列表将在这里动态加载 -->
                </tbody>
            </table>
        </div>
    </div>

    <script src="resources/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            let allTargets = [];
            let currentYear = new Date().getFullYear();
            let allTypes = new Set();
            
            fetch('/vtepobjlist')
                .then(response => response.json())
                .then(data => {
                    allTargets = data.objlist;

                    // 收集所有类型
                    allTargets.forEach(target => {
                        target.obslist.forEach(obs => {
                            if (obs.type) {
                                allTypes.add(obs.type);
                            }
                        });
                    });

                    // 初始化类型筛选器
                    initTypeFilter();

                    // 对Trig_T0进行格式化，去掉尾部的UTC，同时去掉小数点后面的秒。
                    // 增加鲁棒性判断，Trig_T0可能为非时间字符串。无法解析为合法时间的，放到列表末尾。
                    allTargets.forEach(obj => {
                        const raw = obj.Trig_T0;

                        if (typeof raw === 'string') {
                            // 去掉尾部UTC和可能的双引号
                            let cleaned = raw.replace(/UTC"?$/, '');

                            // 去掉小数点及后面的秒
                            cleaned = cleaned.replace(/\.\d+/, '');
                            cleaned = cleaned.replace(" ", '');

                            // 尝试转为 Date 对象
                            const parsedDate = new Date(cleaned);

                            // 检查是否为有效时间
                            if (!isNaN(parsedDate.getTime())) {
                                obj._formatted_T0 = parsedDate;
                            } else {
                                obj._formatted_T0 = null;  // 标记为非法时间
                            }
                        } else {
                            obj._formatted_T0 = null;
                        }
                    });
                    
                    // 排序，非法时间排最后
                    allTargets = allTargets.sort((a, b) => {
                        const timeA = a._formatted_T0;
                        const timeB = b._formatted_T0;

                        tflag = 0; // 都没有，顺序不变
                        if (timeA && timeB) tflag = timeB - timeA;     // 正常比较时间
                        if (timeA && !timeB) tflag = -1;               // a 有时间，排前
                        if (!timeA && timeB) tflag = 1;                // b 有时间，排前
                        // console.log(tflag);
                        return tflag;                                     
                        });
                    // 更新统计信息
                    updateSummary(data.stats);
                    
                    // 初始化年份筛选器
                    initYearFilter();
                    
                    // 默认显示今年的目标
                    // filterTargets(currentYear.toString(), 'all', '');
                    filterTargets('all', 'all', '');
                    
                    // 添加筛选器事件监听
                    document.getElementById('yearFilter').addEventListener('change', applyFilters);
                    document.getElementById('typeFilter').addEventListener('change', applyFilters);
                    document.getElementById('searchInput').addEventListener('input', applyFilters);
                })
                .catch(error => {
                    console.error('Error fetching data:', error);
                    document.getElementById('targetTable').innerHTML = 
                        '<tr><td colspan="9" class="text-center">Failed to load data. Please try again later.</td></tr>';
                });
                
            function initYearFilter() {
                const yearFilter = document.getElementById('yearFilter');
                const years = new Set();
                
                // 提取所有年份
                allTargets.forEach(target => {
                    if (target.Trig_T0) {
                        const year = target.Trig_T0.substring(0, 4);
                        if (year && !isNaN(year)) {
                            years.add(year);
                        }
                    }
                });
                
                // 按降序排序年份
                const sortedYears = Array.from(years).sort((a, b) => b - a);
                
                // 添加年份选项
                sortedYears.forEach(year => {
                    const option = document.createElement('option');
                    option.value = year;
                    option.textContent = year;
                    yearFilter.appendChild(option);
                });
                
                // 设置当前年份为选中
                yearFilter.value = "all";
            }
            
            function initTypeFilter() {
                const typeFilter = document.getElementById('typeFilter');
                
                // 清空现有选项（保留"All Types"选项）
                while (typeFilter.options.length > 1) {
                    typeFilter.remove(1);
                }
                
                // 添加所有类型选项
                Array.from(allTypes).sort().forEach(type => {
                    const option = document.createElement('option');
                    option.value = type;
                    option.textContent = type;
                    typeFilter.appendChild(option);
                });
            }
            
            function applyFilters() {
                const selectedYear = document.getElementById('yearFilter').value;
                const selectedType = document.getElementById('typeFilter').value;
                const searchTerm = document.getElementById('searchInput').value.toLowerCase();
                
                filterTargets(selectedYear, selectedType, searchTerm);
            }
            
            function filterTargets(year, type, searchTerm) {
                let filtered = allTargets;
                
                // 按年份筛选
                if (year !== 'all') {
                    filtered = filtered.filter(target => 
                        target.Trig_T0 && target.Trig_T0.startsWith(year)
                    );
                }
                
                // 按类型筛选
                if (type !== 'all') {
                    filtered = filtered.filter(target => 
                        target.obslist.some(obs => obs.type === type)
                    );
                }
                
                // 按名称搜索
                if (searchTerm) {
                    filtered = filtered.filter(target => 
                        target.obj_name.toLowerCase().includes(searchTerm)
                    );
                }
                
                // 渲染表格
                renderTable(filtered);
                
                // 更新统计信息
                updateFilteredStats(filtered);
            }
            
            function renderTable(targets) {
                const tableBody = document.getElementById('targetTable');
                
                if (targets.length === 0) {
                    tableBody.innerHTML = '<tr><td colspan="9" class="text-center">No targets found matching the selected filters</td></tr>';
                    return;
                }
                
                tableBody.innerHTML = '';
                
                targets.forEach(target => {
                    // 检查是否有quicklook和refined数据
                    // const hasQL = target.obslist.some(obs => obs.quickLook.lightCurveImage);
                    const hasQL = true;
                    const hasRF = target.obslist.some(obs => obs.refined.lightCurveImage);

                    refined_date = cleanTimeString(target.refined_date);

                    
                    const row = document.createElement('tr');  // 这里正确定义了row变量
                    row.innerHTML = `
                        <td>${target.obj_name || ''}</td>
                        <td>${target.Trig_Mission || ''}</td>
                        <td>
                            ${hasQL ? `<span class="data-link" onclick="showDataDetail('${target.obj_name}', 'quicklook')">QL</span>` : '<span class="no-data">QL(N/A)</span>'}
                            ${hasRF ? `<span class="data-link" onclick="showDataDetail('${target.obj_name}', 'refined')">RF</span>` : '<span class="no-data">RF(N/A)</span>'}
                        </td>
                        <td>${target.Trig_T0 || ''}</td>
                        <td>${(target.obj_ra !== undefined && target.obj_ra !== null) ? Number(target.obj_ra).toFixed(5) : ''}</td>
                        <td>${(target.obj_dec !== undefined && target.obj_dec !== null) ? Number(target.obj_dec).toFixed(5) : ''}</td>
                        <td>${target.obj_err || ''}</td>
                        <td>${refined_date}</td>
                        <td>${target.note || ''}</td>
                    `;
                    tableBody.appendChild(row);
                });
            }

            function cleanTimeString(str) {
                if (typeof str !== 'string' || str.trim() === '') {
                    return "";  // 不是字符串或空串，返回 null 表示非法
                }
                // 去掉尾部的 UTC 和可选的双引号
                let cleaned = str.replace(/^"+|"+$/g, '');
                cleaned = cleaned.replace(/UTC"?$/, '');
                // 去掉字符串两端空白
                cleaned = cleaned.trim();
                return cleaned;
            }
            
            function updateSummary(stats) {
                const summary = document.getElementById('summary');
                
                // 创建类型统计HTML
                let typeStatsHTML = '';
                const sortedTypes = Object.keys(stats).filter(key => key !== 'total').sort();
                
                sortedTypes.forEach(type => {
                    typeStatsHTML += `<div class="col-md-2">${type}: ${stats[type]}</div>`;
                });
                
                summary.innerHTML = `
                    <p>Total targets: ${stats.total}</p>
                    <div class="row">
                        ${typeStatsHTML}
                    </div>
                `;
            }
            
            function updateFilteredStats(filteredTargets) {
                // 初始化统计对象
                const filteredStats = {
                    total: filteredTargets.length
                };
                
                // 初始化所有已知类型的计数器
                allTypes.forEach(type => {
                    filteredStats[type] = 0;
                });
                
                // 统计每种类型的数量
                filteredTargets.forEach(target => {
                    target.obslist.forEach(obs => {
                        if (obs.type && filteredStats.hasOwnProperty(obs.type)) {
                            filteredStats[obs.type]++;
                        }
                    });
                });
                
                const summary = document.getElementById('summary');
                
                // 创建类型统计HTML
                let typeStatsHTML = '';
                const sortedTypes = Array.from(allTypes).sort();
                
                sortedTypes.forEach(type => {
                    typeStatsHTML += `<div class="col-md-2">${type}: ${filteredStats[type] || 0}</div>`;
                });
                
                summary.innerHTML = `
                    <p>Showing ${filteredStats.total} targets</p>
                    <div class="row">
                        ${typeStatsHTML}
                    </div>
                `;
            }
            
            // 全局函数，用于在行内点击
            window.showDataDetail = function(targetName, dataType) {
                // 找到该目标的最新refined_date的类型
                const target = allTargets.find(t => t.obj_name === targetName);
                if (!target) return;
                
                // 找到有最新refined_date的观测
                let latestObs = null;
                let latestDate = null;
                
                target.obslist.forEach(obs => {
                    if (obs.refined_date) {
                        const currentDate = new Date(obs.refined_date);
                        if (!latestDate || currentDate > latestDate) {
                            latestDate = currentDate;
                            latestObs = obs;
                        }
                    }
                });
                
                // 如果没有refined_date，选择第一个观测
                if (!latestObs) {
                    latestObs = target.obslist[0];
                }
                const encodedName = encodeURIComponent(targetName);
                const turl = `/vtfollowupep/detail.html?name=${encodedName}&type=${latestObs.type}&dataType=${dataType}`;
                console.log(turl)
                // 跳转到详细页面
                // window.location.href = turl;
                window.open(turl, '_blank')
            };
        });
    </script>
</body>
</html>